package com.hehe.controller.QQ_space;

import com.hehe.DTO.QqSpaceDTO;
import com.hehe.POJO.Qq_space;
import com.hehe.POJO.Qq_space_user_like;
import com.hehe.POJO.User;
import com.hehe.Repository.QQspaceRepository;
import com.hehe.Repository.QQspaceUserLikeRepository;
import com.hehe.Repository.UserRepository;
import com.hehe.Service.UserService;
import jakarta.annotation.Resource;
import jakarta.servlet.http.Cookie;
import jakarta.servlet.http.HttpServletRequest;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Slf4j
@Controller
@RequestMapping(value = "")
public class QQ_space_Controller {

    @Value("${config_file_name}")
    private String config_file_name;




/*  gpt:
建议和最佳实践：
推荐使用  构造函数注入
构造函数注入是 Spring 官方推荐的方式，它能够明确地表达出一个类的依赖关系，
并且可以保证类在被实例化时，所有的依赖都已经设置好。这种方式也使得类在测试时更容易被模拟和替换。
    @Autowired
    public UserController2(UserService userService) {
        this.userService = userService;
    }

避免使用字段注入：字段注入容易导致依赖关系的不可控性和复杂性，尤其是在大型项目中，
它会增加代码的维护成本和理解难度。同时，字段注入也不利于单元测试和依赖注入的可视化管理。
    @Autowired
    public UserService userService;

综上所述，虽然字段注入在某些情况下可能会更加方便，但是为了代码的可维护性和可测试性，
推荐使用构造函数注入作为首选方式。   */

    // 构造函数注入

    @Resource
    private QQspaceRepository qQspaceRepository;

    @Resource
    private QQspaceUserLikeRepository qQspaceUserLikeRepository;

    @Resource
    private UserService userService;

    @Resource
    private UserRepository userRepository;


    // SEO 影响: 如果你的应用涉及到 SEO，重定向可能会影响搜索引擎的索引策略。确保重定向不会引起不必要的重复内容问题。
    // 额外的重定向: 每次访问 /qq-space-list 都会发生一次重定向，这可能略微增加服务器负担。
//    @GetMapping(value = "/qq-space-list")
//    public String sdfsdfgdfg(){
//        return "redirect:/qq-space-list/1";
//    }


    @GetMapping(value = "/qq-space-list/{page}")
    public String index(Model model, @PathVariable Integer page, HttpServletRequest request) {
        log.info("qq-space-list");
        int pageSize = 3;
        int start = (page - 1) * pageSize;
        List<Qq_space> qqSpaceList = qQspaceRepository.findByPage(start, pageSize);
        String usernameByCookie = userService.get_username_by_cookie(request);
        if (usernameByCookie == null) {
            model.addAttribute("user_role", "guest");
        } else {
            User byUsername = userRepository.findByUsername(usernameByCookie);
            if (Objects.equals(byUsername.getRole(), "admin")) {
                model.addAttribute("user_role", "admin");
            } else {
                model.addAttribute("user_role", "user");
            }
        }

        Map<Long, QqSpaceDTO> aggregatedData = new HashMap<>();

        for (Qq_space qqSpace : qqSpaceList) {
            Long id = qqSpace.getId();
            if (!aggregatedData.containsKey(id)) {
                QqSpaceDTO dto = new QqSpaceDTO();
                dto.setId(id);
                dto.setDescription(qqSpace.getDescription());
                dto.setLike_count(qqSpace.getLike_count());
                dto.setUploadDate(qqSpace.getUpload_date());
                dto.setImgPaths(new ArrayList<>());
                aggregatedData.put(id, dto);
            }
            String[] imgPaths = qqSpace.getImg_path().split(",");
            List<String> trimmedPaths = Arrays.stream(imgPaths)
                    .map(String::trim)
                    .toList();
            aggregatedData.get(id).getImgPaths().addAll(trimmedPaths);
        }

        List<QqSpaceDTO> qqSpaceDTOList = new ArrayList<>(aggregatedData.values());
        model.addAttribute("qq_space_list", qqSpaceDTOList);
        return "qq-space/qq_space_list.html";
    }


    @GetMapping(value = "/qq-space-detail/{id}")
    public String qq_space_detail(Model model, @PathVariable long id, HttpServletRequest request) {
        log.info("qq-space-detail");
        Optional<Qq_space> byId = qQspaceRepository.findById(id);
        String usernameByCookie = userService.get_username_by_cookie(request);
        Qq_space_user_like isLike = qQspaceUserLikeRepository.findByUsernameAndQq_space_id(usernameByCookie, id);
        if (isLike != null) {
            model.addAttribute("isLike", true);
        } else {
            model.addAttribute("isLike", false);
        }
        if (byId.isPresent()) {
            Qq_space qq_space = byId.get();
            QqSpaceDTO qqSpaceDTO = new QqSpaceDTO();
            qqSpaceDTO.setId(qq_space.getId());
            qqSpaceDTO.setDescription(qq_space.getDescription());
            qqSpaceDTO.setLike_count(qq_space.getLike_count());
            qqSpaceDTO.setUploadDate(qq_space.getUpload_date());
            String[] imgPaths = qq_space.getImg_path().split(",");
            List<String> trimmedPaths = Arrays.stream(imgPaths)
                    .map(String::trim)
                    .toList();
            qqSpaceDTO.setImgPaths(trimmedPaths);

            model.addAttribute("qqSpaceDTO", qqSpaceDTO);
            return "qq-space/qq-space-detail.html";
        }
        return "redirect:/qq-space-list";
    }


    // ajax fetch
    // 点赞

    // 预防同时点赞出现重复的效果, 添加事务
    @Transactional
    @GetMapping(value = "/qq-space-like/{id}")
    @ResponseBody
    public ResponseEntity<?> space_like(HttpServletRequest request, @PathVariable long id) {
        log.info("qq-space-like");
        Cookie[] cookies = request.getCookies();
        if (cookies == null) {
            return ResponseEntity.status(HttpStatus.UNAUTHORIZED).body("请先登录");
        }
        String username = "";
        if (cookies != null) {
            for (Cookie cookie : cookies) {
                if ("username".equals(cookie.getName())) {
                    username = cookie.getValue();
                }
            }
        }
        //UPDATE users
        //SET age = age + 1
        //WHERE id = 1;
        if (username != null && !username.isEmpty()) {
            Qq_space_user_like byUsernameAndQqSpaceId = qQspaceUserLikeRepository.findByUsernameAndQq_space_id(username, id);
            if (byUsernameAndQqSpaceId == null) {
                byUsernameAndQqSpaceId = new Qq_space_user_like();
                byUsernameAndQqSpaceId.setQq_space_id(id);
                byUsernameAndQqSpaceId.setUsername(username);
                qQspaceUserLikeRepository.save(byUsernameAndQqSpaceId);
                Integer updated = qQspaceRepository.updateLikeCountById(1, id);  // 点赞数 + 1
                System.out.println("==================     // 点赞数 + 1     =====================");
            } else {
                Integer i = qQspaceUserLikeRepository.deleteByUsernameAndQqSpaceId(username, id);
                qQspaceRepository.updateLikeCountById(-1, id);  // 点赞数 - 1
                System.out.println("==================     // 点赞数 - 1     =====================");
            }
        }
        Optional<Qq_space> byId = qQspaceRepository.findById(id);
        if (byId.isPresent()) {
            Qq_space qq_space = byId.get();
            return ResponseEntity.ok(qq_space.getLike_count());
        }
        return ResponseEntity.ok("success");
    }

/*
    @GetMapping(value = "/articles/add")   // get 请求
    public String new_article(Model model) {
        log.info(" 添加文章");
//        model.addAttribute("articles", articleService.findAll());
        return "article/article-add.html";
    }


    @GetMapping("/article/{id}")
    public String aaa(@PathVariable long id, Model model) {
        log.info("文章 by id ");
        Optional<Article> optionalArticle = articleService.findById(id);
        if (optionalArticle.isPresent()) {
            Article article = optionalArticle.get();
            model.addAttribute("article", article);
            return "article/article-detail.html";
        } else {
            // 处理找不到文章的情况
            return "error-page.html"; // 或者返回一个适当的错误视图
        }
    }


    @GetMapping("/article/edit/{id}")
    public String edit(@PathVariable long id, Model model) {
        log.info(" edit  文章 by id ");
        Optional<Article> optionalArticle = articleService.findById(id);
        if (optionalArticle.isPresent()) {
            Article article = optionalArticle.get();
            model.addAttribute("article", article);
            return "article/article-add-edit.html";
        } else {
            // 处理找不到文章的情况
            return "error-page.html"; // 或者返回一个适当的错误视图
        }
    }





    @PostMapping("/article/add")  // post 请求
    public ResponseEntity<?> add_user(@Valid @RequestBody Article article , BindingResult result) {
        if (result.hasErrors()) {
            return ResponseEntity.badRequest().body(result.getAllErrors());
        }
        try {
            articleService.save(article);
//            return ResponseEntity.status(200).body("上传成功");
            return ResponseEntity.ok("上传成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Failed to add article: " + e.getMessage());
        }
    }





        // 上传文章接口, 三个字段:
    // title , content , VerificationCode (验证码)
    @PostMapping("/add-test")
    public ResponseEntity<?> addUser(@RequestBody String requestBody) {
        // 将请求体解析为 JSONObject
        JSONObject jsonObject = new JSONObject(requestBody);
        // 获取请求体中的数据
        String title = jsonObject.getString("title");
        String content = jsonObject.get("content").toString();

        // 保存到数据库
        Article article = new Article();
        article.setTitle(title);
        article.setContent(content);

        try {
            articleService.save(article);
            return ResponseEntity.status(200).body("上传成功");
        } catch (Exception e) {
            return ResponseEntity.badRequest().body("Failed to add article: " + e.getMessage());
        }


    }


//    @GetMapping(value="/article/{id}"  )
//    public String article_detail(Model model){
//        log.info("article_detail.html");
//        return "article_detail.html";
//    }



*/

}




